import { Request, Response } from 'express';
import { asyncHandler, ApiError } from '../middlewares/errorHandler';
import prisma from '../config/database';

// 获取课程列表
export const getCourses = asyncHandler(async (req: Request, res: Response) => {
  const { page = 1, limit = 12, category, level, search } = req.query;

  const skip = (Number(page) - 1) * Number(limit);

  const where: any = {
    status: 'PUBLISHED',
  };

  if (category) {
    where.categoryId = category;
  }

  if (level) {
    where.level = level;
  }

  if (search) {
    where.OR = [
      { title: { contains: search as string } },
      { description: { contains: search as string } },
    ];
  }

  const [courses, total] = await Promise.all([
    prisma.course.findMany({
      where,
      skip,
      take: Number(limit),
      include: {
        teacher: {
          include: {
            user: {
              select: {
                username: true,
                avatar: true,
              },
            },
          },
        },
        category: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
    }),
    prisma.course.count({ where }),
  ]);

  res.json({
    code: 200,
    message: 'Success',
    data: {
      courses,
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total,
        totalPages: Math.ceil(total / Number(limit)),
      },
    },
  });
});

// 获取课程详情
export const getCourseById = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;

  const course = await prisma.course.findUnique({
    where: { id },
    include: {
      teacher: {
        include: {
          user: {
            select: {
              username: true,
              avatar: true,
            },
          },
        },
      },
      category: true,
      chapters: {
        include: {
          lessons: true,
        },
        orderBy: {
          orderIndex: 'asc',
        },
      },
    },
  });

  if (!course) {
    throw new ApiError(404, 'Course not found');
  }

  // 增加浏览量
  await prisma.course.update({
    where: { id },
    data: {
      viewCount: {
        increment: 1,
      },
    },
  });

  res.json({
    code: 200,
    message: 'Success',
    data: course,
  });
});

// 创建课程(教师)
export const createCourse = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;
  const { title, subtitle, description, cover, price, categoryId, level } = req.body;

  // 获取教师信息
  const teacherInfo = await prisma.teacherInfo.findUnique({
    where: { userId },
  });

  if (!teacherInfo) {
    throw new ApiError(403, 'You are not a verified teacher');
  }

  const course = await prisma.course.create({
    data: {
      title,
      subtitle,
      description,
      cover,
      price,
      categoryId,
      level,
      teacherId: teacherInfo.id,
      status: 'DRAFT',
    },
  });

  res.status(201).json({
    code: 201,
    message: 'Course created successfully',
    data: course,
  });
});

// 更新课程
export const updateCourse = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;
  const updateData = req.body;

  const course = await prisma.course.update({
    where: { id },
    data: updateData,
  });

  res.json({
    code: 200,
    message: 'Course updated successfully',
    data: course,
  });
});

// 删除课程
export const deleteCourse = asyncHandler(async (req: Request, res: Response) => {
  const { id } = req.params;

  await prisma.course.delete({
    where: { id },
  });

  res.json({
    code: 200,
    message: 'Course deleted successfully',
    data: null,
  });
});

// 报名课程
export const enrollCourse = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;
  const { id: courseId } = req.params;

  // 检查是否已报名
  const existingEnrollment = await prisma.enrollment.findUnique({
    where: {
      userId_courseId: {
        userId,
        courseId,
      },
    },
  });

  if (existingEnrollment) {
    throw new ApiError(400, 'Already enrolled in this course');
  }

  // 创建报名记录
  const enrollment = await prisma.enrollment.create({
    data: {
      userId,
      courseId,
    },
  });

  // 更新课程学生数
  await prisma.course.update({
    where: { id: courseId },
    data: {
      studentCount: {
        increment: 1,
      },
    },
  });

  res.status(201).json({
    code: 201,
    message: 'Enrolled successfully',
    data: enrollment,
  });
});

// 获取我的已报名课程
export const getEnrolledCourses = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;

  const enrollments = await prisma.enrollment.findMany({
    where: { userId },
    include: {
      course: {
        include: {
          teacher: {
            include: {
              user: {
                select: {
                  username: true,
                  avatar: true,
                },
              },
            },
          },
        },
      },
    },
    orderBy: {
      createdAt: 'desc',
    },
  });

  res.json({
    code: 200,
    message: 'Success',
    data: enrollments,
  });
});

// 更新学习进度
export const updateLearningProgress = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.user!.userId;
  const { lessonId } = req.params;
  const { watchedDuration, lastPosition, isCompleted } = req.body;

  const progress = await prisma.learningProgress.upsert({
    where: {
      userId_lessonId: {
        userId,
        lessonId,
      },
    },
    update: {
      watchedDuration,
      lastPosition,
      isCompleted,
    },
    create: {
      userId,
      lessonId,
      watchedDuration,
      lastPosition,
      isCompleted,
    },
  });

  res.json({
    code: 200,
    message: 'Progress updated successfully',
    data: progress,
  });
});
